<?php

/**

 * 新闻动态
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Index\Controller;

use Think\Controller;

class NewsController extends BaseController {

    public $webid;

    public function _initialize() {
        parent::_initialize();
        $this->title = '新闻动态';
        $webid = M('web')->where('webname="新闻动态"')->getField('id');
        $this->webid = $webid;
    }

    //新闻动态首页 by qiaoshoujuan 20171013
    public function index() {
        //未读新闻
        $map['READERS'] = array('notlike', "%" . session('user_id') . "%");
        $unread = M('news')->field('NEWS_ID,READERS')->where($map)->select();

        //已读新闻
        $map['READERS'] = array('like', "%" . session('user_id') . "%");
        $read = M('news')->field('NEWS_ID,READERS')->where($map)->select();

        //查看当前用户是否有权限新建新闻动态
        $user_priv = explode(",", session("user_priv_other") . session("user_priv"));

        $privs = explode(",", "1,355,362,376,383,395,397,398");
        $is_show = 1;
//        foreach ($user_priv as $k => $v) {
//            if (in_array($v, $privs)) {
//                $is_show = 1;
//            }
//        }
        $this->is_show = $is_show;
        $this->read = count($read);
        $this->unread = count($unread);
        $this->display();
    }

    //查看未读、已读新闻
    public function view() {
        $is_read = I('get.is_read');
        if ($is_read == 'unread') {
            $map['READERS'] = array('notlike', "%" . session('user_id') . "%");
        } elseif ($is_read == 'read') {
            $map['READERS'] = array('like', "%" . session('user_id') . "%");
        }
        $news = M('news')->field('NEWS_ID,SUBJECT,ATTACHMENT_ID,ATTACHMENT_NAME,CLICK_COUNT,NEWS_TIME,READERS,PROVIDER,UPLOADS,UPLOADS_URL')->where($map)->order('NEWS_ID desc')->limit('0,10')->select();
        foreach ($news as $key => $row) {
            //修改时间
            $news[$key]['news_time'] = explode(' ', $row['news_time'])[0];
            if ($row['attachment_id']) {
                $attaId = explode(',', $row['attachment_id']);
                $attaName = explode('*', $row['attachment_name']);
                $pcPic = downloadFile($attaId[0], $attaName[0], 'news');
//                if ($pcPic) {
//                    $size = getimagesize($pcPic[0]['url']);
//                    if ($size[0] > $size[1]) {
//                        $news[$key]['url'] = $pcPic[0]['url'];
//                    }
//                }
                $news[$key]['url'] = $pcPic[0]['url'];
            } else {
                $uploadUrl = explode(';', $row['uploads_url']);
                $size = getimagesize('.' . $uploadUrl[0]);
                if ($size[0] > $size[1]) {
                    $news[$key]['url'] = $uploadUrl[0];
                }else{
                    $news[$key]['url'] = '';
                }
            }
        }
//print_r($news);
        $this->news = $news;
        $this->is_read = $is_read;
        $this->display();
    }

    //新闻管理
    public function lists() {
        $news = M('news')->field('NEWS_ID,TYPE_ID,SUBJECT,CONTENT,NEWS_TIME,READERS,PROVIDER')->where("PROVIDER = '" . session('user_id') . "'")->order('NEWS_ID desc')->limit('0,10')->select();

        $this->news = $news;
        $this->display();
    }

    //新闻详情
    public function show() {
        $news_id = I('get.news_id');
        $new = M('news')->where('NEWS_ID = ' . $news_id)->find();
        $new['content'] = str_replace(' ', "<br/>", $new['content']);
        if ($new['last_edit_time'] == '0000-00-00 00:00:00') {
            $new['last_edit_time'] = $new['news_time'];
        }
        $new['news_time'] = date("Y-m-d", strtotime($new['news_time']));

        //获取PC端文件
        $ispc = 0;
        if ($new['attachment_name']) {
            $uploads = downloadFile($new['attachment_id'], $new['attachment_name'], 'news', $new['uploads'], $new['uploads_url']);
            $ispc = 1;
//如果下载成功，保存至本地并取出附件
//            if ($data['uploads']) {
//                M('news')->where('NEWS_ID = ' . $news_id)->save($data);
//                //获取附件
//                $uploads = M('news')->where('NEWS_ID=' . $news_id)->getField('uploads_url');
//                $uploads = explode(';', rtrim($uploads, ';'));
//            }
        }

        $this->ispc = $ispc;

        if ($new['uploads_url']) {
            $names = explode(';', rtrim($new['uploads'], ';'));
            $urls = explode(';', rtrim($new['uploads_url'], ';'));
            for ($i = 0; $i < count($urls); $i++) {
                if ($urls[$i]) {
                    $uploads[$i]['name'] = $names[$i];
                    $uploads[$i]['url'] = $urls[$i];
                }
            }
        }
        //相关评论
        $comments = M('news_comment')->field("COMMENT_ID,NEWS_ID,USER_ID,CONTENT,RE_TIME")->where("NEWS_ID = " . $news_id)->select();
        foreach ($comments as $k => $v) {
            if ($new['anonymity_yn'] == 0) {
                getChineseName();
                $comments[$k]['user_name'] = getChineseName($v['user_id']);
            } elseif ($new['anonymity_yn'] == 1) {
                $comments[$k]['user_name'] = "匿名";
            }
            //判断当前用户是否是新闻发布者、是否该条新闻的评论者，是否有权限删除评论
            if ($new['provider'] == session("user_id") || $v['user_id'] == session("user_id")) {
                $comments[$k]['is_del'] = 1;
            }
        }
        //更新点击量
        $sql1 = "update `news` set CLICK_COUNT = CLICK_COUNT + 1 where NEWS_ID = " . $news_id;
        $r1 = M('')->execute($sql1);

        //更新阅读者
        if (!strstr($new['readers'], session('user_id'))) {
            $readers = $new['readers'] . session('user_id') . ",";
            $sql2 = "update `news` set readers = '" . $readers . "' where NEWS_ID = " . $news_id;
            $r2 = M('')->execute($sql2);
        }
        $this->new = $new;
        $this->uploads = $uploads;
        $this->comments = $comments;
        $this->count = count($comments);
        $this->display();
    }

    //新闻动态评论
    public function commentNews() {
        if (IS_AJAX) {
            $data = I('post.');
            //添加news表
            $cdata['NEWS_ID'] = $data['news_id'];
            $cdata['USER_ID'] = session('user_id');
            $cdata['CONTENT'] = $data['content'];
            $cdata['RE_TIME'] = date('Y-m-d H:i:s');
            $res = M('news_comment')->add($cdata);

            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('show', array('news_id' => $data['news_id']));
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }
    }

    private function getNewsData($limit, $is_read) {
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);
        if ($is_read == 'unread') {
            $map['READERS'] = array('notlike', "%" . session('user_id') . "%");
        } elseif ($is_read == 'read') {
            $map['READERS'] = array('like', "%" . session('user_id') . "%");
        }
        if ($limit) {

            $lists = M('news')->field('NEWS_ID,SUBJECT,CLICK_COUNT,TYPE_ID,CONTENT,NEWS_TIME')->where($map)->order('NEWS_ID desc')->limit($start, $limit)->select();
        } else {
            $lists = M('news')->field('NEWS_ID,SUBJECT,CLICK_COUNT,TYPE_ID,CONTENT,NEWS_TIME')->where($map)->order('NEWS_ID desc')->select();
        }
        foreach ($lists as $k => $v) {
            $lists[$k]['subject_info'] = mb_substr($v['subject'], 0, 15, "utf-8") . "…";
        }
        return $lists;
    }

    //下拉加载更多
    public function dropload() {
        $limit = $this->limit;
        $is_read = I('get.is_read');
        $lists = $this->getNewsData($limit, $is_read);
//        print_r($lists);die;
//        foreach ($lists as $key => $row) {
//            if ($row['news_time'] !== '0000-00-00') {
//                $lists[$key]['news_time'] = date('Y-m-d', strtotime($row['news_time']));
//            }
//        }
        $this->ajaxReturn($lists);
    }

    //添加新闻动态
    public function addNews() {
        if (IS_AJAX) {
            $data = I('post.');
            if ($data['news_id']) {
                //修改news
                $pdata['NEWS_ID'] = $data['news_id'];
                $pdata['SUBJECT'] = $data['subject'];
                $pdata['CONTENT'] = $data['content'];
                $pdata['LAST_EDIT_TIME'] = date('Y-m-d H:i:s');
                $pdata['ANONYMITY_YN'] = $data['anonymity_yn'];
                $pdata['TYPE_ID'] = $data['type_id'];
                $pdata['uploads'] = $data['uploads'];
                $pdata['uploads_url'] = $data['uploads_url'];
                if (!empty($data['dept_ids'])) {
                    $pdata['TO_ID'] = implode(',', $data['dept_ids']) . ',';
                } else {
                    $pdata['TO_ID'] = 'ALL_DEPT';
                }
                if (!empty($data['priv_id']))
                    $pdata['PRIV_ID'] = implode(',', $data['priv_id']) . ',';
                if (!empty($data['user_id']))
                    $pdata['USER_ID'] = implode(',', $data['user_id']) . ',';
                $res = M('news')->save($pdata);

                if ($res !== false) {
                    $return['info'] = '修改成功';
                    $return['url'] = U('lists');
                } else {
                    $return['info'] = '修改失败';
                }
                $this->ajaxReturn($return);
            } else {
                //添加news表
                $cdata['SUBJECT'] = $data['subject'];
                $cdata['PROVIDER'] = session('user_id');
                $cdata['CONTENT'] = $data['content'];
                $cdata['NEWS_TIME'] = date('Y-m-d H:i:s');
                $cdata['ANONYMITY_YN'] = $data['anonymity_yn'];
                $cdata['TYPE_ID'] = $data['type_id'];
                $cdata['uploads'] = $data['uploads'];
                $cdata['uploads_url'] = $data['uploads_url'];
                $cdata['is_mobile'] = 1;
                if (!empty($data['dept_ids'])) {
                    $cdata['TO_ID'] = implode(',', $data['dept_ids']) . ',';
                } else {
                    $cdata['TO_ID'] = 'ALL_DEPT';
                }
                if (!empty($data['priv_id']))
                    $cdata['PRIV_ID'] = implode(',', $data['priv_id']) . ',';
                if (!empty($data['user_id']))
                    $cdata['USER_ID'] = implode(',', $data['user_id']) . ',';

                $res = M('news')->add($cdata);
                if ($res !== false) {
                    //添加新闻提醒
                    $row = M('news')->where('NEWS_ID = ' . $res)->find();
                    //部门
                    $deptUsers = getDeptUsers($row['to_id']);
                    //角色
                    if (!empty($row['priv_id'])) {
                        $privUsers = getPrivUsers($row['priv_id']);
                    } else {
                        $privUsers = [];
                    }
                    //用户
                    if (!empty($row['user_id'])) {
                        $user = explode(',', $row['user_id']);
                    } else {
                        $user = [];
                    }
                    $users = array_merge($deptUsers, $privUsers, $user);
                    $users = array_unique($users);
                    $content = '请查看新闻！标题：<a href="http://www.jsumt.com:88/index.php/Index/News/show/news_id/' . $row['news_id'] . '">' . $row['subject'] . '</a>，发送人：' . getChineseName($row['provider']) . '。';
                    setWeixinMsg($users, $content, $this->webid);

                    $return['info'] = '提交成功';
                    $return['url'] = U('view', array("is_read" => "unread"));
                } else {
                    $return['info'] = '提交失败';
                }
                $this->ajaxReturn($return);
            }
        }
        $news_id = I('get.news_id');
        if ($news_id) {
            $new = M('news')->field('NEWS_ID,SUBJECT,CLICK_COUNT,TYPE_ID,CONTENT,NEWS_TIME,READERS,PROVIDER,ANONYMITY_YN,LAST_EDIT_TIME,uploads,uploads_url')->where("NEWS_ID = " . $news_id)->find();
            $this->new = $new;
        }
        if (!empty($new['uploads_url'])) {
            $names = explode(';', rtrim($new['uploads'], ';'));
            $urls = explode(';', rtrim($new['uploads_url'], ';'));
            for ($i = 0; $i < count($urls); $i++) {
                if ($urls[$i]) {
                    $uploads[$i]['name'] = $names[$i];
                    $uploads[$i]['url'] = $urls[$i];
                }
            }
            $this->uploads = $uploads;
        }

        $this->sub = date('Y-m-d') . ' ' . getChineseWeek(date('w'));
        $this->time = date('Y-m-d H:i:s');

        $this->display();
    }

    //删除新闻评论
    public function delComment() {
        $comment_id = I('comment_id');
        $res = M('news_comment')->where('COMMENT_ID=' . $comment_id)->delete();
        if ($res) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }

    //删除新闻
    public function delNews() {
        $news_id = I('news_id');
        $row = M('news')->where('NEWS_ID=' . $news_id)->find();

        if ($row['uploads_url']) {
            $urls = explode(';', ltrim($row['uploads_url'], ';'));
            foreach ($urls as $url) {
                @unlink('.' . $url);
            }
        }

        $res = M('news')->where('NEWS_ID=' . $news_id)->delete();
        if ($res) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }

    private function getEnglishName($name) {
        $sql = "select USER_ID from `user` where USER_NAME = '" . $name . "'";
        $englishName = M("user")->query($sql);
        return $englishName[0]["user_id"];
    }

    //新闻查询
    public function searchNews() {
        if (IS_AJAX) {
            $data = I("post.");
            $condition = ' where 1';
            if ($data['provider']) {
                $data['provider'] = $this->getEnglishName($data['provider']);
                $condition .= " and PROVIDER = '" . $data['provider'] . "'";
            }

//            print_r($data);die;
            if ($data['type_id'] != 0) {
                $condition .= " and TYPE_ID = '" . $data['type_id'] . "'";
            }
            if ($data['subject']) {
                $condition .= " and SUBJECT like '%" . $data['subject'] . "%'";
            }
            if ($data['date_start']) {
                $condition .= " and NEWS_TIME >= '" . substr($data['date_start'], 0, 10) . "'";
            }
            if ($data['date_end']) {
                $condition .= " and NEWS_TIME <= '" . substr($data['date_end'], 0, 10) . "'";
            }
            if ($data['content']) {
                $condition .= " and CONTENT like '%" . $data['content'] . "%'";
            }
            $sql = "select NEWS_ID,SUBJECT,CLICK_COUNT,TYPE_ID,NEWS_TIME from `news` " . $condition . " order by NEWS_TIME desc";
            $news = M('')->query($sql);
            foreach ($news as $k => $v) {
                $news[$k]['subject_info'] = mb_substr($v['subject'], 0, 15, "utf-8") . "…";
            }
            $this->ajaxReturn($news);
        }
        $this->display();
    }

    //获取日期
    public function getDate() {
        $date = strtotime(I('date'));
        $newData = I('date') . ' ' . getChineseWeek(date('w', $date));
        $this->ajaxReturn($newData);
    }

    public function upload() {
        $this->upfile('./Public/Uploads/news/');
    }

}
